package dexter.core.coord;

import java.io.IOException;
import java.util.Hashtable;
import java.util.Properties;

import dexter.net.Consumer;
import dexter.net.msg.common.RequestListener;
import dexter.util.Configuration;
import dexter.util.IdGenerator;
import dexter.util.PropertiesReader;
import dexter.aware.Sensor;
import dexter.core.host.HostAddress;

public class Coordinator {

	private Properties props;
	private Consumer consumer;
	private Hashtable<String, String> jobs;
	
	private static String status;

	public Coordinator(Properties props) {
		this.props = props;
		int port = Configuration.getCoordPort();
		consumer = new Consumer(port);
		jobs = new Hashtable<String, String>();
		
	}
		
	public String generateJob(String groupId) {
		
		String jobId = IdGenerator.generate();
		while (jobs.containsKey(jobId)) jobId = IdGenerator.generate();
		
		jobs.put(jobId, groupId);
		return jobId;
	}
	
	public String finishJob(String jobId) {
		String groupId = jobs.remove(jobId);
	    return groupId;
    }
	
	public static String getStatus() {		
		return status;
	}
	
	public static void setStatus(String s) {
	    status = s;	
	}
	
	public Properties getConfig() {
		return props;
	}

	public void start(){
		  
		  RequestListener clistener = new CoordListener(this);
		  try {
			consumer.receive(clistener);
			System.out.println("Coordinator: Waiting for test requests");
		} catch (IOException e) {
			e.printStackTrace();
		}
		 
	}
	
	public static void main(String[] args) {
		
		System.out.println("COORDINATOR INIT");
		
		//Read main parameters
		String config="config.properties";
		
		for(int i=0; i<args.length; i+=2){
			if(args[i].equals("-p")){
				config=args[i+1];
			}		
		}	
		System.out.println(config);
		Properties props=PropertiesReader.getProperties(config);
		
		Coordinator coord = new Coordinator(props);
		
		int PORT = Configuration.getCoordPort();
		System.out.println("Coordinator: Opening port "+PORT);
		coord.start();
		
//		String fronthost = props.getProperty("front_host");
//		int frontport = Integer.parseInt(props.getProperty("front_port"));
//		
//		HostAddress front = new HostAddress(fronthost,frontport);
		Sensor sensor = new Sensor();		
		sensor.start();
		
		System.out.println("COORDINATOR END");
		
	}




}
